package org.spring.aicloud.controller.model;

import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.spring.aicloud.entity.Answer;
import org.spring.aicloud.entity.myenum.AiModelEnum;
import org.spring.aicloud.entity.myenum.AiTypeEnum;
import org.spring.aicloud.service.IAnswerService;
import org.spring.aicloud.util.AppVariable;
import org.spring.aicloud.util.ResponseEntity;
import org.spring.aicloud.util.SecurityUtil;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 调用本地的OpenAI大模型
 */
@RestController
@RequestMapping("/chatgpt")
public class ChatGPTController {

    @Resource
    private IAnswerService answerService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private OllamaChatClient ollamaChatClient;
    /**
     * 调用OpenAi的聊天接口
     * @param question
     * @return
     */
    @RequestMapping("/chat")
    public ResponseEntity chat(String question){
        if (!StringUtils.hasLength(question)){
            return ResponseEntity.fail("问题不能为空");
        }
        //在调用接口之前，先针对用户加锁
        //创建key
        String lockKey = AppVariable.getModelLockKey
                (SecurityUtil.getCurrentUser().getUid(),
                        AiModelEnum.OPENAI.getValue(), AiTypeEnum.CHAT.getValue());
        String result = ""; //大模型返回的结果
        boolean save = false;//数据是否保存成功
        //创建分布式锁实例
        RLock lock = redissonClient.getLock(lockKey);
        //尝试获取分布式锁
        boolean isLock = false;
        try {
            isLock = lock.tryLock(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (!isLock) {
            //获取分布式锁失败
            return ResponseEntity.fail("请勿频繁调用接口");
        }
        try {
            //获取锁成功，开始执行业务逻辑
            //调用openAI接口
            result = ollamaChatClient.call(question);
            //将结果保存到数据库中
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setType(AiTypeEnum.CHAT.getValue());
            answer.setModel(AiModelEnum.OPENAI.getValue());
            //根据SpringSecurity获取当前登录的用户id
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            save = answerService.save(answer);
        }catch (Exception ignored){}
        finally {
            //释放锁
            lock.unlock();
        }
        if (!save){
            return ResponseEntity.fail("数据保存失败!");
        }
        return ResponseEntity.success(result);
    }

}
